<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>查询用户学习记录</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 40px auto;
            max-width: 800px;
            padding: 0 20px;
            background: #f7f9fc;
            color: #333;
        }
        h1 {
            color: #0b3d91;
        }
        input[type="text"] {
            width: 100%;
            padding: 10px 15px;
            font-size: 16px;
            border: 2px solid #0b3d91;
            border-radius: 5px;
            transition: border-color 0.3s ease;
            box-sizing: border-box;
        }
        input[type="text"]:focus {
            outline: none;
            border-color: #0056d2;
        }
        ul#suggestions {
            list-style: none;
            margin-top: 10px;
            padding-left: 0;
            background: white;
            border: 1px solid #0b3d91;
            border-radius: 5px;
            max-height: 300px;
            overflow-y: auto;
            box-shadow: 0 0 10px rgb(0 0 0 / 0.1);
        }
        ul#suggestions li {
            padding: 8px 15px;
            cursor: pointer;
            border-bottom: 1px solid #ddd;
        }
        ul#suggestions li:hover {
            background-color: #f1f7ff;
        }
        .no-data {
            margin-top: 10px;
            font-style: italic;
            color: #666;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 25px;
        }
        table, th, td {
            border: 1px solid #aaa;
        }
        th, td {
            padding: 8px 10px;
            text-align: left;
        }
        th {
            background-color: #f0f6ff;
        }
        #back-button {
            margin-top: 20px;
            padding: 8px 14px;
            font-size: 14px;
            background: #0b3d91;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: none;
        }
        #back-button:hover {
            background: #0056d2;
        }
        #pagination-wrapper {
            display: none;
            margin-top: 20px;
            text-align: center;
        }
        #pagination-wrapper input[type="number"] {
            width: 60px;
            padding: 5px;
            font-size: 14px;
            border: 1px solid #aaa;
            border-radius: 4px;
            appearance: textfield;
        }
        #pagination-wrapper input[type="number"]::-webkit-outer-spin-button,
        #pagination-wrapper input[type="number"]::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
        #pagination-wrapper button {
            margin: 0 3px;
            padding: 6px 10px;
            font-size: 14px;
            border: 1px solid #aaa;
            background: white;
            cursor: pointer;
            border-radius: 4px;
        }
        #pagination-wrapper button.active {
            background: #0b3d91;
            color: white;
        }
        #pagination-wrapper button:hover {
            background: #e0e0e0;
        }
    </style>
</head>
<body>

<h1 id="search-title">输入用户名</h1>
<input type="text" id="username" placeholder="输入用户名自动搜索..." autocomplete="off" />
<ul id="suggestions"></ul>

<button id="back-button">返回搜索</button>

<h2 id="record-title" style="display:none;"></h2>
<table id="record-table" style="display:none;">
    <thead>
    <tr>
        <th>ID</th>
        <th>学习日期</th>
        <th>学习时间</th>
        <th>学习进度</th>
        <th>学习内容</th>
        <th>录入时间</th>
    </tr>
    </thead>
    <tbody id="record-body"></tbody>
</table>

<div id="pagination-wrapper">
    <div id="pagination" style="display:inline-block;"></div>
    <input type="number" id="page-input" min="1" />
    <button id="jump-button">跳转</button>
</div>

<script>
    const input = document.getElementById('username');
    const suggestions = document.getElementById('suggestions');
    const title = document.getElementById('record-title');
    const table = document.getElementById('record-table');
    const tableBody = document.getElementById('record-body');
    const backBtn = document.getElementById('back-button');
    const paginationDiv = document.getElementById('pagination');
    const paginationWrapper = document.getElementById('pagination-wrapper');
    const pageInput = document.getElementById('page-input');
    const jumpButton = document.getElementById('jump-button');
    const searchTitle = document.getElementById('search-title');

    let timer = null;
    let currentUserId = null;
    let currentUsername = null;
    let currentPage = 1;
    let totalPages = 1;

    input.addEventListener('input', () => {
        const keyword = input.value.trim();
        clearTimeout(timer);

        if (!keyword) {
            suggestions.innerHTML = '';
            return;
        }

        timer = setTimeout(async () => {
            try {
                const res = await fetch(`/api/users/search?keyword=${encodeURIComponent(keyword)}`);
                const users = await res.json();

                if (!Array.isArray(users) || users.length === 0) {
                    suggestions.innerHTML = '<li class="no-data">无匹配用户</li>';
                    return;
                }

                suggestions.innerHTML = users.map(user =>
                    `<li data-userid="${user.id}">${user.username}</li>`
                ).join('');

            } catch (e) {
                suggestions.innerHTML = '<li class="no-data" style="color:red;">搜索失败</li>';
            }
        }, 300);
    });

    suggestions.addEventListener('click', async (e) => {
        const li = e.target;
        const userId = li.getAttribute('data-userid');
        const username = li.textContent;

        if (!userId) return;

        currentUserId = userId;
        currentUsername = username;
        input.value = '';
        suggestions.innerHTML = '';

        input.style.display = 'none';
        suggestions.style.display = 'none';
        searchTitle.style.display = 'none';

        await loadPage(1);
    });

    async function loadPage(page) {
        try {
            const res = await fetch(`/api/records/user/page/${currentUserId}?page=${page}`);
            const data = await res.json();
            const records = data.data;
            totalPages = Math.ceil(data.total / 20);
            currentPage = page;

            title.style.display = 'block';
            title.textContent = `${currentUsername} 的学习记录（第 ${page} 页） 来源：${data.source}`;
            table.style.display = 'table';
            backBtn.style.display = 'inline-block';
            paginationWrapper.style.display = 'block';

            if (!Array.isArray(records) || records.length === 0) {
                tableBody.innerHTML = `<tr><td colspan="6" style="text-align:center; color:gray;">无学习记录</td></tr>`;
                paginationDiv.innerHTML = '';
                return;
            }

            tableBody.innerHTML = records.map(r => `
                <tr>
                    <td>${r.id}</td>
                    <td>${r.studyDate}</td>
                    <td>${r.studyTime} 分钟</td>
                    <td>${r.progress}%</td>
                    <td>${r.content || '-'}</td>
                    <td>${r.createdAt}</td>
                </tr>
            `).join('');

            renderPagination();
            scrollToTop();  // 新增：每次翻页滚动到顶部
        } catch (err) {
            alert('查询学习记录失败！');
        }
    }

    function renderPagination() {
        let html = '';

        if (currentPage > 1) {
            html += `<button onclick="loadPage(${currentPage - 1})">上一页</button>`;
        }

        const start = Math.max(1, currentPage - 3);
        const end = Math.min(totalPages, start + 6);

        for (let i = start; i <= end; i++) {
            html += `<button class="${i === currentPage ? 'active' : ''}" onclick="loadPage(${i})">${i}</button>`;
        }

        if (currentPage < totalPages) {
            html += `<button onclick="loadPage(${currentPage + 1})">下一页</button>`;
        }

        paginationDiv.innerHTML = html;
    }

    function handleJump() {
        const targetPage = parseInt(pageInput.value);
        if (!isNaN(targetPage) && targetPage >= 1 && targetPage <= totalPages) {
            loadPage(targetPage);
        }
    }

    jumpButton.addEventListener('click', handleJump);

    pageInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            handleJump();
        }
    });

    backBtn.addEventListener('click', () => {
        input.value = '';
        input.style.display = 'block';
        suggestions.style.display = 'block';
        searchTitle.style.display = 'block';
        suggestions.innerHTML = '';
        title.style.display = 'none';
        table.style.display = 'none';
        backBtn.style.display = 'none';
        paginationWrapper.style.display = 'none';
        currentUserId = null;
        currentUsername = null;
    });

    function scrollToTop() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    }
</script>

</body>
</html>